import React from 'react';
import { Modal, Form, Select, notification, Input } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { usersList, editUser } from '@/services/api';
import { SIZE, PAGE } from '@/utils/constant';

interface props {
  onClose: () => void;
  dispatch: any;
  roleData: any[];
  searchValue: any;
}

interface UserFormProps extends FormComponentProps {
  ref: any;
  usersData: any;
}

const ref: any = React.createRef();
const { Item } = Form;
const MyForm = Form.create<UserFormProps>()(({ form: { getFieldDecorator }, usersData }: any) => {
  const formItemLayout = {
    labelCol: {
      xs: { span: 4, offset: 4 },
    },
    wrapperCol: {
      sm: { span: 8 },
    },
  };

  return (
    <Form layout="horizontal" {...formItemLayout}>
      <Item label="姓名">
        {getFieldDecorator('name', {
          initialValue: usersData.name,
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(<Input placeholder="请选择" />)}
      </Item>
      <Item label="性别">
        {getFieldDecorator('sex', {
          initialValue: usersData.sex + '',
          rules: [
            {
              required: true,
              message: '必填',
            },
          ],
        })(
          <Select
            placeholder="请选择"
            allowClear
            showSearch
            filterOption={(input: any, option: any) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            <Select.Option value="1">男</Select.Option>
            <Select.Option value="2">女</Select.Option>
            <Select.Option value="3">保密</Select.Option>
          </Select>,
        )}
      </Item>
    </Form>
  );
});

const EditUserModal = ({ roleData, searchValue, onClose, dispatch }: props) => {
  const usersData = JSON.parse(sessionStorage.getItem('usersData') || '');

  return (
    <Modal
      visible
      onCancel={onClose}
      maskClosable={false}
      title="编辑用户"
      onOk={() => {
        ref.current.validateFields((err: any, val: any) => {
          if (!err) {
            const newValue: any = {};
            newValue.id = usersData.id;
            newValue.name = val.name;
            newValue.image_id = usersData.image_id;
            newValue.sex = val.sex;
            newValue.course = usersData.course;
            newValue.role_id = usersData.role_id;
            delete usersData.image;
            delete usersData.roles;
            editUser({ ...usersData, ...newValue }).then((resp: any) => {
              if (resp.status === 'success') {
                notification.success({ message: '用户编辑成功' });
                onClose();
                dispatch({
                  type: 'OPEN_LOADING',
                });
                usersList({ ...searchValue, page: PAGE, size: SIZE })
                  .then((res: any) => {
                    if (res.status === 'success') {
                      dispatch({
                        type: 'GET_DATA',
                        payload: res.data.data,
                      });
                      dispatch({
                        type: 'CHANGE_PAGINATION',
                        payload: {
                          total: res.data.meta.total,
                        },
                      });
                    }
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  })
                  .catch(() => {
                    dispatch({
                      type: 'CLOSED_LOADING',
                    });
                  });
              }
            });
          }
        });
      }}
    >
      <MyForm ref={ref} usersData={usersData} />
    </Modal>
  );
};

export default EditUserModal;
